﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Winista.Text.HtmlParser;
using Winista.Text.HtmlParser.Filters;
using Winista.Text.HtmlParser.Lex;
using Winista.Text.HtmlParser.Nodes;
using Winista.Text.HtmlParser.Tags;
using Winista.Text.HtmlParser.Util;

namespace WBInfo
{
    public class WBInfoAction
    {
        public static Dictionary<string,object> getSearchNowData()
        {
            string html;
            Dictionary<string,object> outAry = new Dictionary<string, object>();
            List<string> result = new List<string>();
            try
            {
                html = HttpClient.HttpGet("https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6");
                Lexer lexer = new Lexer(html);
                Parser parser = new Parser(lexer);
                //筛选要查找的对象 这里查找td，封装成过滤器
                NodeFilter filter = new TagNameFilter("table");
                NodeList htmlNodes = parser.Parse(filter);
                ITag tag = (htmlNodes[0] as ITag);
                NodeList test = tag.Children;
                bool flag = false;
                for (int i = 0; i < test.Size(); i++)
                {
                
                    if (test[i] is TagNode)
                    {
                        TagNode node = (TagNode)test[i];
                        if (node.TagName == "TBODY")
                        {
                            if (!flag)
                            {
                                flag = true;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    if (flag && test[i] is TableRow)
                    {
                        string content = test[i].Children[3].ToHtml();
                        Regex reg = new Regex(@"(?is)<a(?:(?!href=).)*href=(['""]?)(?<url>[^""\s>]*)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>");
                        MatchCollection mc = reg.Matches(content);
                        foreach (Match m in mc)
                        {
                            result.Add(m.Groups["text"].Value);
                        }
                    }
                }
                outAry.Add("result","success");
                outAry.Add("data",result);
            }
            catch (Exception e)
            {
                outAry.Add("result",e.Message);
            }
            return outAry;
        }
    }
}